const { app, BrowserWindow } = require('electron');
const path = require('path');

const { getProjectDirectoriesIPC } = require('@ipc/getProjectDirectoriesIPC');  // 项目布局目录树

const logger = require('@utils/logger');
const fileHandler = require('@utils/fileHandle');
const { createAppServer } = require('@server/clientServer');
const { isDev } = require('@utils/helper');
const colors = require('colors');
const gs = require('@utils/globalStore.js');

let mainWindow;

function createMainWindow() {

    logger.warn('[+----+]Creating main window...');

    mainWindow = new BrowserWindow({
        // width: 1300,
        // height: 670,
        x: 1,
        y: 10,
        width: 1000,
        height: 698,
        show: false,
        autoHideMenuBar: true,
        webPreferences: {
            preload: fileHandler.getPreloadPath(),
            contextIsolation: true,
            nodeIntegration: false,
            sandbox: false,
            webviewTag: true, // 确保启用 webview 标签                      
            // 设置内容安全策略
            contentSecurityPolicy: "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline';",
            clipboardWrite: true // 开启剪贴板写入权限
        },
        icon: path.join(__dirname, '../dist/icon.icns')// TODO：区分系统
    });

    createAppServer();

    logger.log('[+10002]main window __dirname:::', __dirname);


    mainWindow.loadURL(fileHandler.getloadUrl()).then(() => {
        console.log('[+000000]页面加载成功'.red);
    }).catch((err) => {
        console.error('[+-1-1-1]页面加载失败:', err);
    });

    // // 拦截导航事件
    // mainWindow.webContents.on('will-navigate', (event, url) => {
    //     event.preventDefault(); // 阻止默认导航行为
    // });

    // 主窗口加载完成后显示
    mainWindow.once('ready-to-show', () => {
        mainWindow.show();
    });

    mainWindow.setTitle('esv2');

    // projectr tree ipc
    if (!gs.get('ipc-start')) {
        getProjectDirectoriesIPC(mainWindow);
        gs.set('ipc-start', true);
    }

    // only show in dev
    if (isDev()) {
        console.log('[+10018] mainWindow test 【NODE_ENV】:: '.bgBlue, process.env.NODE_ENV.yellow);
        const { maxSort } = require('@utils/maxSort');
        maxSort(path.join(app.getAppPath(), 'app'));
        mainWindow.webContents.openDevTools();
    }

    mainWindow.webContents.setWindowOpenHandler((details) => {
        shell.openExternal(details.url)
        return { action: 'deny' }
    })

    mainWindow.webContents.on('did-finish-load', () => {
        if (!app.isPackaged) {

        }
    });
}

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        logger.log('[+*****+] 监测到窗口重新获得焦点，准备重绘窗口');
        createMainWindow();
    }
});

app.on('window-all-closed', () => {
    logger.warn('[+----+] main window closing...');
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

// 优雅退出
if (process.platform === 'win32') {
    process.on('message', (data) => {
        if (data === 'graceful-exit') {
            // if (global.wssServer) global.wssServer.close()
            app.quit();
        }
    });
} else {
    process.on('SIGTERM', () => {
        // if (global.wssServer) global.wssServer.close()
        app.quit();
    });
}


module.exports = { createMainWindow };
